package com.atguigu.spzx.manager.auth;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            this.responseNoLoginInfo(response);
            return false;
        }

        String sysUserInfoJson = stringRedisTemplate.opsForValue().get("user:login:" + token);
        if (StringUtils.isEmpty(sysUserInfoJson)){
            this.responseNoLoginInfo(response);
            return  false;
        }

        ThreadLocalUtil.setSysUser(JSON.parseObject(sysUserInfoJson,SysUser.class));
        stringRedisTemplate.expire("user:login:" + token , 30 , TimeUnit.MINUTES) ;

        return true ;
    }

    private void responseNoLoginInfo(HttpServletResponse response) {

        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        String jsonResult208 = JSON.toJSONString(result);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        writer.write(jsonResult208);
        if(writer!=null){
            writer.close();
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //视图渲染之后（请求完全的处理结束）
        ThreadLocalUtil.removeSysUser();
    }
}
